package com.stylefeng.guns.modular.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.Tools.CodeMsg;
import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.validater.Insert;
import com.stylefeng.guns.core.validater.Update;
import com.stylefeng.guns.modular.system.model.SysDict;
import com.stylefeng.guns.modular.system.service.ISysDictService;
import com.stylefeng.guns.modular.system.warpper.DictWarpper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 系统字典表
 *
 * @author 张亚林
 * @Date 2018-10-30 17:07
 */
@Controller
@RequestMapping(value = {"/gunsApi/auth/sysDict"})
@Api(value = "系统字典表操作相关api", tags = {"系统字典表操作接口"})
public class SysDictController extends BaseController {
    @Autowired
    private ISysDictService sysDictService;
	
    /**
     * 分页获取系统字典表列表
     * @param sysDict
     * @param pageNum
     * @param pageSize
     * @return	
     */
    @ApiOperation(value = "分页获取系统字典表列表", notes = "分页获取系统字典表列表", httpMethod = "POST")
    @PostMapping(value = "/pageList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)	
    @ResponseBody
    public Result pageList(
        @RequestBody @ApiParam(name = "sysDict", value = "系统字典表对象")SysDict sysDict,
        @ApiParam(name = "pageNum", value = "当前页数", required = true) @RequestParam(value = "pageNum", required = true) Integer pageNum,
        @ApiParam(name = "pageSize", value = "每页显示条数", required = true) @RequestParam(value = "pageSize", required = true) Integer pageSize		
        ) {
        try {
            Pager pager=new Pager();
            pager.setPageNumber(pageNum);//页码从1 开始
            pager.setPageSize(pageSize);
            pager.setObj(sysDict);
            Map map=sysDictService.pageListSysDict(pager,getToken());
            if(map!=null && map.size()>0){
                List<SysDict> list=(List<SysDict>)map.get("rows");
                if(list!=null && list.size()>0){
                    List<Map<String, Object>> mList=new ArrayList<>();
                    for (SysDict o:list){
                        Map map_= BeanUtil.beanToMap(o);
                        mList.add(map_);
                    }
                    super.warpObject(new DictWarpper(mList));
                    BeanUtil.setFieldValue(map,"rows",mList);
                }
            }
            return Result.success(map);
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 获取系统字典表列表
     * @param sysDict    
     * @return	
     */
    @ApiOperation(value = "获取系统字典表列表", notes = "获取系统字典表列表", httpMethod = "POST")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)	
    @ResponseBody
    public Result list(
        @RequestBody @ApiParam(name = "sysDict", value = "系统字典表对象")SysDict sysDict) {
        try {
            List<SysDict> list=sysDictService.selectListSysDict(sysDict,getToken());
            List<Map<String, Object>> mList=new LinkedList<>();
            if(list!=null && list.size()>0){
                for (SysDict o:list){
                    Map map= BeanUtil.beanToMap(o);
                    mList.add(map);
                }
            }
            return Result.success(super.warpObject(new DictWarpper(mList)));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 通过主键获取系统字典表对象
     * @param id
     * @return
     */
    @ApiOperation(value = "通过主键获取系统字典表对象", notes = "通过主键获取系统字典表对象", httpMethod = "GET")
    @GetMapping(value = "/getById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getById(
            @ApiParam(name = "id", value = "主键ID", required = true) @RequestParam(value = "id", required = true) String  id
    ) {
        try {
            SysDict sysDict=sysDictService.findSysDictById(id,getToken());
            List<Map<String, Object>> mList=new LinkedList<>();
            if(sysDict!=null){
                Map map= BeanUtil.beanToMap(sysDict);
                mList.add(map);
            }
            return Result.success(super.warpObject(new DictWarpper(mList)));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }

    /**
     * 新增系统字典表数据
     *
     * @param sysDict 
     * @param result
     * @return
     */
    @ApiOperation(value = "新增系统字典表数据", notes = "新增系统字典表数据", httpMethod = "POST")
    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "新增系统字典表数据")
    @ResponseBody
    public Result add(@Validated(value = Insert.class) @RequestBody @ApiParam(name = "sysDict ", value = "系统字典表对象")SysDict sysDict ,BindingResult result
    ) {
        if (result.hasErrors()) {
            return Result.error(CodeMsg.SERVER_EXCEPTION,"参数异常！");
        }
        try {
            String code=sysDict.getCode();
            Integer pid=sysDict.getPid();
            if(pid==null||pid.equals(0)){
                pid=new Integer(0);
                Wrapper<SysDict> wrapper=new EntityWrapper<>();
                wrapper.eq("code", code).and();
                wrapper.eq("pid", pid);
                SysDict dict=this.sysDictService.selectOne(wrapper);
                if(dict!=null){
                 return Result.error(CodeMsg.DICT_INSERT_ERROR);
                }
            }
            return Result.success(this.sysDictService.insert(sysDict));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }


    /**
     * 更新系统字典表数据
     * @param sysDict
     * @param result
     * @return
     */
    @ApiOperation(value = "更新系统字典表数据", notes = "更新系统字典表数据", httpMethod = "POST")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "更新系统字典表数据")
    @ResponseBody
    public Result update(@Validated(value = Update.class) @RequestBody @ApiParam(name = "sysDict", value = "系统字典表对象")SysDict sysDict, BindingResult result
    ) {
        if (result.hasErrors()) {
            return Result.error(CodeMsg.SERVER_EXCEPTION,"参数异常！");
        }
        try {
            sysDictService.updateSysDict(sysDict,getToken());
            return Result.success();
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 删除系统字典表数据
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除系统字典表数据", notes = "删除系统字典表数据", httpMethod = "GET")
    @GetMapping(value = "/delBatch", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除系统字典表数据")
    @ResponseBody
    public Result delBatch(
            @ApiParam(name = "ids", value = "主键ID字符数组", required = true) @RequestParam(value = "ids", required = true) String ids
    ) {
        try {
            sysDictService.deleteBatchSysDict(ids.split(","),getToken());
            return Result.success();
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
	/**
     * 删除系统字典表数据
     * @param sysDict
     * @return
     */
    @ApiOperation(value = "删除系统字典表数据", notes = "删除系统字典表数据", httpMethod = "POST")
    @PostMapping(value = "/del", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除系统字典表数据")
    @ResponseBody
    public Result del(@RequestBody @ApiParam(name = "sysDict", value = "系统字典表对象")SysDict sysDict) {
        try {
            sysDictService.deleteSysDict(sysDict,getToken());
            return Result.success();
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 获取系统字典表的Key-Value列表，用于html的Select数据源
     * @param sysDict
     * @return
     */
    @ApiOperation(value = "获取系统字典表的Key-Value列表，用于html的Select数据源", notes = "获取系统字典表的Key-Value列表，用于html的Select数据源", httpMethod = "POST")
    @PostMapping(value = "/optionsList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result optionsList(@RequestBody @ApiParam(name = "sysDict", value = "系统字典表对象")SysDict sysDict) {
        try {
            return Result.success(sysDictService.optionsSysDict(sysDict,getToken()));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
	private String getToken(){		
		return getHttpServletRequest().getHeader("Authorization").substring(7);
    }
}
